<?php

/**
 *
 * Class to handle SSO validation and submission (create SSO for other sites)
 *
 *
 * $Id: SSO.php 1774 2012-04-09 10:52:45Z locth $
 * $Author: nhudt $
 *
 */
class SGN_SSO
{
    private static $_ssoLog = '/home/sgn/logs/sso.log';
    private static $_validatedAccountName = '';
    /**
     * 
     * Refresh SSO
     * 
     * @return void
     * 
     */
    public static function refresh($hardRefresh = false)
    {
        $session = SGN_Application::get('session');
//        $accountName = $session->get('username');
        $accountName = self::validate(SGN_Application::getConfig('sgn', 'sso'), $hardRefresh);
        if(!$accountName){
            SGN_Application::set('userId', null);
            //SGN_Application::set('profile', new stdClass());
            SGN_Application::set('profile', Application_Model_SGN_Profile::factory(1));
            
            $session->set('username', null);
            $session->set('loggedin', 0);
            $session->set('userId', 0);
            $session->set('isSGNAccount', 0);
            return;
        }
        
        $forceLogin = false;
        if(SGN_Application::isInternalUser()){
            $forceLoginAccountName = $session->get('forceLoginAccountName');
            if($forceLoginAccountName){
                $accountName = $forceLoginAccountName;
                $forceLogin = true;
            }
        }
        
        //restore session
        $session->set('loggedin', 1);
        $session->set('username', $accountName);
        if($forceLogin){
            $profile = Application_Model_SGN_Profile::factory($accountName, true);
        } else {
            $profile = Application_Model_SGN_Profile::factory(SGN_Application::get('vngSession')->uin);
        }
        
        if ($profile->getUserId()) {
            $session->set('isSGNAccount', 1);
        }
        SGN_Application::set('account', $profile);
        SGN_Application::set('profile', $profile);
        $userId = $profile->getUserId();
        SGN_Application::set('userId', $userId);
        SGN_Application::set('username', $accountName);
        $session->set('userId', $userId);
        $model = Application_Model_SGN_Login::factory();
        if($userId){
            $model->checkLastLoginDate($accountName, $userId);
        }
        
        //rewrite cookie
        SGN_Application::setCookie(APPLICATION_ENV.'_loggedin', 1);
        SGN_Application::setCookie(APPLICATION_ENV.'_username', $accountName);
        SGN_Application::setCookie(APPLICATION_ENV . 'userId', $userId);
        return;
    }
    /**
     *
     * POST to SSO2 Session server to validate SSO
     * - If $hardRefresh is TRUE then revalidate SSO Session
     *
     * @param array $config
     * @param boolean $hardRefresh
     *
     * @return string username
     *
     */
    public static function validate($config = null, $hardRefresh = false)
    {
        if (self::$_validatedAccountName && !$hardRefresh) {
            return self::$_validatedAccountName;
        }
        $vngSession = SSO_CSSO::checkVNGSession(SSO_CSSO::getCookies());
        SGN_Application::set('vngSession', $vngSession);
        if (SGN_Application::isRegistered('profiler')) {
            SGN_Application::get('profiler')->setProfilerData('username', $vngSession->accountName, 'userinfo');
        }
        self::$_validatedAccountName = $vngSession->accountName;
        return $vngSession->accountName;
    }

    public static function jump($accountname, $successUrl = '', $product = 'laio')
    {
        // check input
        if(!$accountname || !$product){
            return '';
        }

        // get product config
        $apiConfig = SGN_Application::getConfig('sgn', 'api');
        $productConfig = $apiConfig->get('jump')->get($product)->toArray();
        if ($productConfig['code'] != $product) {
            //error: invalid product code
            return -1;
        }

        // jump via GIS app.zing.vn
        $baseUrl = SGN_Application::get('baseUrl').'/'.SGN_Application::get('module');
        $ssoConfig = SGN_Application::getConfig('sgn', 'sso')->toArray();
        $sign = md5($accountname . $ssoConfig['appId'] . $ssoConfig['secureId'] . SGN_Application::getCurrentTime());
        if(!$successUrl){
            $successUrl = $baseUrl.$productConfig['endpoint'];
        }

        $failUrl = $baseUrl.SGN_Application::getConfig('sgn', 'site', 'url')->get('accountFail').'?params=';
        $gisURL = sprintf($apiConfig->get('jump')->get('gis')->get('jumper'),
                            $accountname,
                            $sign,
                            SGN_Application::getCurrentTime(),
                            $ssoConfig['appId'],
                            $ssoConfig['groupSgn'],
                            $successUrl,
                            $failUrl);

        // redirect to endpoint
        header("Location: $gisURL");
        exit;
    }

    public static function parseSsoParam($params)
    {
        $accountName = null;
        if($params){
            $params = explode('.', $params);
            array_shift($params);
            array_pop($params);
            array_pop($params);
            array_pop($params);
            array_pop($params);
            $accountName = implode('.', $params);
        }
        return $accountName;
    }

    /**
     *
     * Post to GIS PlayEZ
     *
     * @param string $url sso validation URL
     * @param  array
     * @return string
     */
    public static function postData($url, $fieldsData)
    {
        $startTime = microtime(true);
        $ch = curl_init($url);
        $key = isset($_COOKIE['skey']) ? $_COOKIE['skey'] : '';
        $acn = isset($_COOKIE['acn']) ? $_COOKIE['acn'] : '';
        $uin = isset($_COOKIE['uin']) ? $_COOKIE['uin'] : '';
        $time = isset($_COOKIE['sTime']) ? $_COOKIE['sTime'] : '';
        $vngauth = isset($_COOKIE['vngauth']) ? $_COOKIE['vngauth'] : '';
        $acs = isset($_COOKIE['acs']) ? $_COOKIE['acs'] : '';
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsData);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_COOKIE, "skey=$key;acn=$acn;uin=$uin;sTime=$time;vngauth=" . urlencode($vngauth) . ";acs=$acs");
        curl_setopt($ch, CURLOPT_HEADER, 0); // DO NOT RETURN HTTP HEADERS
        $returnData = curl_exec($ch);
        if (SGN_Application::isRegistered('profiler')) {
            $totalTime = (microtime(true) - $startTime) * 1000; // in miliseconds
            SGN_Application::get('profiler')->setProfilerData('REST_API', array("$url", $totalTime, serialize($fieldsData)));
        }
        if (! curl_error($ch)) {
            return $returnData;
        } else {
            throw new SGN_Exception(curl_error($ch));
        }
    }
}